package com.dq.controller;

import com.dq.dto.LoginDTO;
import com.dq.dto.PasswordDto;
import com.dq.mapper.AdminMapper;
import com.dq.pojo.Admin;
import com.dq.service.Impl.AdminServiceImpl;
import com.dq.utils.BaseContext;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/admin")
@Api(value = "(admin)", tags = "(admin)接口API")
@Slf4j
public class AdminController {

    @Value("${avatar.path}")
    private String path;

    @Autowired
    private AdminServiceImpl adminService;

    @Autowired
    private AdminMapper adminMapper;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody LoginDTO loginDTO, HttpServletRequest request) {
        log.info("登录: {}", loginDTO);

        Map<String, Object> map = new HashMap<>();

        Admin admin = new Admin();
        BeanUtils.copyProperties(loginDTO, admin);
        String code = request.getSession().getAttribute("captcha").toString();

        admin = adminService.login(admin);

        if (!Objects.equals(loginDTO.getCaptcha(), code)) {
            map.put("code", 2);
            map.put("data", "");
            map.put("msg", "验证码错误");

            return map;
        }

        if (admin != null && admin.getPassword().equals(loginDTO.getPassword())) {
            map.put("code", 0);
            map.put("data", "");
            map.put("msg", "登陆成功");

            request.getSession().setAttribute("admin", admin.getId().toString());

        } else {
            map.put("code", 1);
            map.put("data", "");
            map.put("msg", "账号或密码错误");
        }

        return map;
    }

    @PostMapping("/exit")
    public Map<String, Object> exit(HttpServletRequest request) {
        log.info("退出");

        Map<String, Object> map = new HashMap<>();

        request.getSession().invalidate();

        map.put("code", 0);
        map.put("data", "");
        map.put("msg", "退出成功");

        return map;
    }

    @PostMapping("/updateAvatar")
    public Map<String, Object> updateAvatar(@RequestParam("file") MultipartFile file) throws IOException {

        // 生成一个唯一的文件名，使用 UUID
        String uniqueFileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();

        // 目录路径
        String directoryPath = "C:\\Users\\Administrator\\IdeaProjects\\dly_2024_1_14\\src\\main\\resources\\static\\avatar\\";

        directoryPath = path;

        // 完整的目标路径
        Path destinationPath = Paths.get(directoryPath, uniqueFileName);

        Files.copy(file.getInputStream(), destinationPath, StandardCopyOption.REPLACE_EXISTING);

        return adminService.updateAvatar(uniqueFileName);

    }

    @PostMapping("/getInfo")
    public Map<String, Object> getInfo(){

        return adminService.selectById();

    }

    @PostMapping("/updateInfo")
    public Map<String, Object> updateInfo(@RequestBody PasswordDto passwordDto){

        String oldP = passwordDto.getOldPassword();
        String newP1 = passwordDto.getNewPassword1();
        String newP2 = passwordDto.getNewPassword2();

        Admin admin = adminMapper.selectById(BaseContext.getCurrentId());

        Map<String, Object> r = new HashMap<>();

        if(!Objects.equals(oldP, admin.getPassword())){
            r.put("code", 1);
            r.put("data", "");
            r.put("msg", "");

            return r;
        }

        if(!Objects.equals(newP1, newP2)){
            r.put("code", 2);
            r.put("data", "");
            r.put("msg", "");

            return r;
        }

        admin.setPassword(newP1);
        adminMapper.updateInfo(admin);

        r.put("code", 0);
        r.put("data", "");
        r.put("msg", "");

        return r;
    }

    @GetMapping("/getAvatar")
    public void getAvatar(HttpServletRequest request, HttpServletResponse response) throws IOException {

        Long id = BaseContext.getCurrentId();

        Admin admin = adminMapper.selectById(id);

        // 生成一个唯一的文件名，使用 UUID
        String uniqueFileName = admin.getAvatarName();

        // 目录路径
        String directoryPath = "C:\\Users\\Administrator\\IdeaProjects\\dly_2024_1_14\\src\\main\\resources\\static\\avatar\\";

        directoryPath = path;

        String filePath = directoryPath + uniqueFileName;

        // 2. 从指定的文件路径读取图片文件
        File imageFile = new File(filePath);

        // 检查文件是否存在
        if (imageFile.exists()) {
            // 读取图片文件并转换为RenderedImage
            BufferedImage bufferedImage = ImageIO.read(imageFile);

            // 设置响应内容类型为图片
            response.setContentType("image/png");

            // 将图片写入响应输出流
            ImageIO.write(bufferedImage, "png", response.getOutputStream());
        } else {
            // 处理文件不存在的情况
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

}
